using Microsoft.AspNetCore.Mvc;
using SG3L_RAG.Application.Interfaces;
using SG3L_RAG.Domain.Entities;

namespace SG3L_RAG.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class PermissionsController : ControllerBase
    {
        private readonly IPermissionService _permissionService;

        public PermissionsController(IPermissionService permissionService)
        {
            _permissionService = permissionService;
        }

        /// <summary>
        /// 获取所有权限
        /// </summary>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Permission>>> GetAllPermissions()
        {
            var permissions = await _permissionService.GetAllAsync();
            return Ok(permissions);
        }

        /// <summary>
        /// 根据ID获取权限
        /// </summary>
        [HttpGet("{id}")]
        public async Task<ActionResult<Permission>> GetPermission(Guid id)
        {
            var permission = await _permissionService.GetByIdAsync(id);
            if (permission == null)
            {
                return NotFound($"权限 {id} 不存在");
            }
            return Ok(permission);
        }

        /// <summary>
        /// 根据文档ID获取权限列表
        /// </summary>
        [HttpGet("document/{documentId}")]
        public async Task<ActionResult<IEnumerable<Permission>>> GetPermissionsByDocument(Guid documentId)
        {
            var permissions = await _permissionService.GetByDocumentIdAsync(documentId);
            return Ok(permissions);
        }

        /// <summary>
        /// 根据用户ID获取权限列表
        /// </summary>
        [HttpGet("user/{userId}")]
        public async Task<ActionResult<IEnumerable<Permission>>> GetPermissionsByUser(Guid userId)
        {
            var permissions = await _permissionService.GetByUserIdAsync(userId);
            return Ok(permissions);
        }

        /// <summary>
        /// 根据权限类型获取权限列表
        /// </summary>
        [HttpGet("type/{permissionType}")]
        public async Task<ActionResult<IEnumerable<Permission>>> GetPermissionsByType(string permissionType)
        {
            var permissions = await _permissionService.GetByPermissionTypeAsync(permissionType);
            return Ok(permissions);
        }

        /// <summary>
        /// 获取特定用户对特定文档的权限
        /// </summary>
        [HttpGet("document/{documentId}/user/{userId}")]
        public async Task<ActionResult<Permission>> GetUserDocumentPermission(Guid documentId, Guid userId)
        {
            var permission = await _permissionService.GetPermissionAsync(documentId, userId);
            if (permission == null)
            {
                return NotFound($"用户 {userId} 对文档 {documentId} 没有权限");
            }
            return Ok(permission);
        }

        /// <summary>
        /// 检查用户是否有特定权限
        /// </summary>
        [HttpGet("document/{documentId}/user/{userId}/check")]
        public async Task<ActionResult<bool>> CheckPermission(
            Guid documentId, 
            Guid userId, 
            [FromQuery] string permissionType)
        {
            var hasPermission = await _permissionService.HasPermissionAsync(documentId, userId, permissionType);
            return Ok(hasPermission);
        }

        /// <summary>
        /// 创建新权限
        /// </summary>
        [HttpPost]
        public async Task<ActionResult<Permission>> CreatePermission([FromBody] CreatePermissionRequest request)
        {
            try
            {
                var permission = await _permissionService.CreateAsync(
                    request.DocumentId, 
                    request.UserId, 
                    request.PermissionType);
                return CreatedAtAction(nameof(GetPermission), new { id = permission.Id }, permission);
            }
            catch (Exception ex)
            {
                return BadRequest($"创建权限失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新权限
        /// </summary>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdatePermission(Guid id, [FromBody] Permission permission)
        {
            if (id != permission.Id)
            {
                return BadRequest("权限ID不匹配");
            }

            try
            {
                await _permissionService.UpdateAsync(permission);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"更新权限失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除权限
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeletePermission(Guid id)
        {
            try
            {
                await _permissionService.DeleteAsync(id);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"删除权限失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 授予权限
        /// </summary>
        [HttpPost("grant")]
        public async Task<IActionResult> GrantPermission([FromBody] GrantPermissionRequest request)
        {
            try
            {
                await _permissionService.GrantPermissionAsync(
                    request.DocumentId, 
                    request.UserId, 
                    request.PermissionType);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"授予权限失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 撤销权限
        /// </summary>
        [HttpPost("revoke")]
        public async Task<IActionResult> RevokePermission([FromBody] RevokePermissionRequest request)
        {
            try
            {
                await _permissionService.RevokePermissionAsync(request.DocumentId, request.UserId);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"撤销权限失败: {ex.Message}");
            }
        }
    }

    // 请求模型
    public class CreatePermissionRequest
    {
        public Guid DocumentId { get; set; }
        public Guid UserId { get; set; }
        public string PermissionType { get; set; } = string.Empty;
    }

    public class GrantPermissionRequest
    {
        public Guid DocumentId { get; set; }
        public Guid UserId { get; set; }
        public string PermissionType { get; set; } = string.Empty;
    }

    public class RevokePermissionRequest
    {
        public Guid DocumentId { get; set; }
        public Guid UserId { get; set; }
    }
}
